package com.yupi.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.annotation.OperationLog;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.model.dto.operation.OperationAddRequest;
import com.yupi.springbootinit.model.dto.operation.OperationQueryRequest;
import com.yupi.springbootinit.model.dto.operation.OperationUpdateRequest;
import com.yupi.springbootinit.model.entity.Operation;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.OperationVO;
import com.yupi.springbootinit.service.OperationService;
import com.yupi.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;

/**
 * 工序库接口
 */
@RestController
@RequestMapping("/operation")
@Slf4j
public class OperationController {

    @Resource
    private OperationService operationService;

    @Resource
    private UserService userService;

    /**
     * 创建工序库
     *
     * @param operationAddRequest 创建请求
     * @param request             HTTP请求
     * @return 新创建的工序库id
     */
    @PostMapping("/add")
    @OperationLog(operation = "新增", module = "工序库")
    public BaseResponse<Long> addOperation(@RequestBody OperationAddRequest operationAddRequest, HttpServletRequest request) {
        if (operationAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Operation operation = new Operation();
        BeanUtils.copyProperties(operationAddRequest, operation);
        operationService.validOperation(operation, true);
        User loginUser = userService.getLoginUser(request);
        boolean result = operationService.save(operation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(operation.getId());
    }

    /**
     * 删除工序库
     *
     * @param deleteRequest 删除请求
     * @param request       HTTP请求
     * @return 是否删除成功
     */
    @PostMapping("/delete")
    @OperationLog(operation = "删除", module = "工序库")
    public BaseResponse<Boolean> deleteOperation(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        Operation oldOperation = operationService.getById(id);
        ThrowUtils.throwIf(oldOperation == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取当前登录用户（用于日志记录）
        User loginUser = userService.getLoginUser(request);
        boolean result = operationService.removeById(id);
        return ResultUtils.success(result);
    }

    /**
     * 更新工序库（仅管理员）
     *
     * @param operationUpdateRequest 更新请求
     * @param request               HTTP请求
     * @return 是否更新成功
     */
    @PostMapping("/update")
    @OperationLog(operation = "修改", module = "工序库")
    public BaseResponse<Boolean> updateOperation(@RequestBody OperationUpdateRequest operationUpdateRequest, 
                                               HttpServletRequest request) {
        if (operationUpdateRequest == null || operationUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Operation operation = new Operation();
        BeanUtils.copyProperties(operationUpdateRequest, operation);
        // 参数校验
        operationService.validOperation(operation, false);
        long id = operationUpdateRequest.getId();
        // 判断是否存在
        Operation oldOperation = operationService.getById(id);
        ThrowUtils.throwIf(oldOperation == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取当前登录用户（用于日志记录）
        User loginUser = userService.getLoginUser(request);
        boolean result = operationService.updateById(operation);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取工序库
     *
     * @param id 工序库id
     * @return 工序库信息
     */
    @GetMapping("/get")
    public BaseResponse<Operation> getOperationById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Operation operation = operationService.getById(id);
        if (operation == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(operation);
    }

    /**
     * 根据 id 获取工序库（封装类）
     *
     * @param id 工序库id
     * @return 工序库VO
     */
    @GetMapping("/get/vo")
    public BaseResponse<OperationVO> getOperationVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Operation operation = operationService.getById(id);
        if (operation == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(operationService.getOperationVO(operation));
    }

    /**
     * 分页获取工序库列表（仅管理员）
     *
     * @param operationQueryRequest 查询请求
     * @return 工序库分页列表
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Operation>> listOperationByPage(@RequestBody OperationQueryRequest operationQueryRequest,
                                                           HttpServletRequest request) {
        if (operationQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = operationQueryRequest.getCurrent();
        long size = operationQueryRequest.getPageSize();
        
        // 添加调试日志
        log.info("分页查询工序库(管理员) - current: {}, size: {}", current, size);
        
        // 参数校验
        ThrowUtils.throwIf(current <= 0, ErrorCode.PARAMS_ERROR, "页码必须大于0");
        ThrowUtils.throwIf(size <= 0, ErrorCode.PARAMS_ERROR, "页面大小必须大于0");
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR, "页面大小不能超过20");
        
        Page<Operation> operationPage = operationService.page(new Page<>(current, size),
                operationService.getQueryWrapper(operationQueryRequest));
        return ResultUtils.success(operationPage);
    }

    /**
     * 分页获取工序库列表（封装类）
     *
     * @param operationQueryRequest 查询请求
     * @return 工序库VO分页列表
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<OperationVO>> listOperationVOByPage(@RequestBody OperationQueryRequest operationQueryRequest,
                                                               HttpServletRequest request) {
        if (operationQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = operationQueryRequest.getCurrent();
        long size = operationQueryRequest.getPageSize();
        
        // 添加调试日志
        log.info("分页查询工序库 - current: {}, size: {}", current, size);
        
        // 参数校验
        ThrowUtils.throwIf(current <= 0, ErrorCode.PARAMS_ERROR, "页码必须大于0");
        ThrowUtils.throwIf(size <= 0, ErrorCode.PARAMS_ERROR, "页面大小必须大于0");
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR, "页面大小不能超过20");
        
        Page<Operation> operationPage = operationService.page(new Page<>(current, size),
                operationService.getQueryWrapper(operationQueryRequest));
        return ResultUtils.success(operationService.getOperationVOPage(operationPage));
    }
}